<template>
  <div class="role-container">
    <div class="header-actions">
      <h2>角色列表</h2>
      <button class="add-btn" @click="showAddForm = true">添加角色</button>
    </div>

    <!-- 添加角色表单 -->
    <div class="add-form-container" v-if="showAddForm">
      <div class="add-form">
        <h3>添加新角色</h3>
        <div class="form-group">
          <label>角色名称:</label>
          <input type="text" v-model="newRole.roleName" placeholder="请输入角色名称" />
        </div>
        <div class="form-group">
          <label>角色标识:</label>
          <input type="text" v-model="newRole.roleKey" placeholder="请输入角色标识" />
        </div>
        <div class="form-group">
          <label>权限菜单:</label>
          <div class="menu-options">
            <label v-for="(menu, index) in menuOptions" :key="index" class="menu-option">
              <input type="checkbox" v-model="newRole.roleMenuArr" :value="menu" />
              {{ menu }}
            </label>
          </div>
        </div>
        <div class="form-actions">
          <button class="cancel-btn" @click="showAddForm = false">取消</button>
          <button class="submit-btn" @click="addRole">提交</button>
        </div>
      </div>
    </div>

    <!-- 编辑角色表单 -->
    <div class="add-form-container" v-if="showEditForm">
      <div class="add-form">
        <h3>编辑角色</h3>
        <div class="form-group">
          <label>角色名称:</label>
          <input type="text" v-model="editRole.roleName" placeholder="请输入角色名称" />
        </div>
        <div class="form-group">
          <label>权限菜单:</label>
          <div class="menu-options">
            <label v-for="(menu, index) in menuOptions" :key="index" class="menu-option">
              <input type="checkbox" v-model="editRole.roleMenuArr" :value="menu" />
              {{ menu }}
            </label>
          </div>
        </div>
        <div class="form-actions">
          <button class="cancel-btn" @click="showEditForm = false">取消</button>
          <button class="submit-btn" @click="updateRole">保存</button>
        </div>
      </div>
    </div>

    <div class="role-table">
      <table>
        <thead>
          <tr>
            <th>角色ID</th>
            <th>角色名称</th>
            <th>权限</th>
            <th>排序号</th>
            <th>状态</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="item in list" :key="item._id">
            <td>{{ item.roleKey }}</td>
            <td>{{ item.roleName }}</td>
            <td>
              <span v-for="(menu, index) in item.roleMenuArr" :key="index">
                {{ menu }}{{ index < item.roleMenuArr.length - 1 ? '，' : '' }}
              </span>
            </td>
            <td>{{ item.sortNum }}</td>
            <td>{{ item.status === 1 ? '启用' : '禁用' }}</td>
            <td>
              <button class="edit-btn" @click="openEditForm(item)">编辑</button>
              <button class="delete-btn" @click="deleteRole(item._id)">删除</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  data() {
    return {
      list: [],
      showAddForm: false,
      showEditForm: false,
      newRole: {
        roleName: '',
        roleKey: '',
        roleMenuArr: [],
      },
      editRole: {
        _id: '',
        roleName: '',
        roleMenuArr: [],
      },
      menuOptions: ['全部权限', '用户管理', '角色管理', '部门管理', '订单管理', '商品管理'],
    }
  },
  methods: {
    fetchRoles() {
      axios
        .get('http://47.94.6.186:3001/admin/role', {
          headers: {
            token: localStorage.getItem('loginToken'),
          },
        })
        .then((res) => {
          console.log(res.data.data)
          this.list = res.data.data
        })
    },
    addRole() {
      if (
        !this.newRole.roleName ||
        !this.newRole.roleKey ||
        this.newRole.roleMenuArr.length === 0
      ) {
        alert('请填写完整的角色信息')
        return
      }

      axios
        .post(
          'http://47.94.6.186:3001/admin/role',
          {
            roleName: this.newRole.roleName,
            roleKey: this.newRole.roleKey,
            roleMenuArr: this.newRole.roleMenuArr,
          },
          {
            headers: {
              token: localStorage.getItem('loginToken'),
            },
          },
        )
        .then((res) => {
          console.log('添加角色响应:', res.data)
          // 不再严格判断code === 200，只要请求成功就认为操作成功
          alert('添加角色成功')
          this.showAddForm = false
          this.newRole = {
            roleName: '',
            roleKey: '',
            roleMenuArr: [],
          }
          this.fetchRoles() // 重新获取角色列表
        })
        .catch((error) => {
          console.error('添加角色出错:', error)
          alert('添加角色出错，请检查网络连接')
        })
    },
    openEditForm(role) {
      this.editRole = {
        _id: role._id,
        roleName: role.roleName,
        roleMenuArr: [...role.roleMenuArr], // 创建数组的副本
      }
      this.showEditForm = true
    },

    updateRole() {
      if (!this.editRole.roleName || this.editRole.roleMenuArr.length === 0) {
        alert('请填写完整的角色信息')
        return
      }

      axios
        .patch(
          `http://47.94.6.186:3001/admin/role/${this.editRole._id}`,
          {
            roleName: this.editRole.roleName,
            roleMenuArr: this.editRole.roleMenuArr,
          },
          {
            headers: {
              token: localStorage.getItem('loginToken'),
            },
          },
        )
        .then((res) => {
          console.log('更新角色响应:', res.data)
          alert('更新角色成功')
          this.showEditForm = false
          this.fetchRoles() // 重新获取角色列表
        })
        .catch((error) => {
          console.error('更新角色出错:', error)
          alert('更新角色出错，请检查网络连接')
        })
    },

    deleteRole(roleId) {
      if (confirm('确定要删除这个角色吗？')) {
        axios
          .delete(`http://47.94.6.186:3001/admin/role/${roleId}`, {
            headers: {
              token: localStorage.getItem('loginToken'),
            },
          })
          .then((res) => {
            console.log('删除角色响应:', res.data)
            // 不再严格判断code === 200，只要请求成功就认为操作成功
            alert('删除角色成功')
            this.fetchRoles() // 重新获取角色列表
          })
          .catch((error) => {
            console.error('删除角色出错:', error)
            alert('删除角色出错，请检查网络连接')
          })
      }
    },
  },
  mounted() {
    this.fetchRoles()
  },
}
</script>

<style scoped>
.role-container {
  padding: 20px;
  position: relative;
}

.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

h2 {
  margin: 0;
  color: #333;
}

.add-btn {
  background-color: #1976d2;
  color: white;
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-weight: bold;
}

.add-form-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.add-form {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  width: 500px;
  max-width: 90%;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

.form-group input {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.menu-options {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 5px;
}

.menu-option {
  display: flex;
  align-items: center;
  gap: 5px;
  cursor: pointer;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.cancel-btn {
  background-color: #9e9e9e;
  color: white;
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.submit-btn {
  background-color: #4caf50;
  color: white;
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.role-table {
  width: 100%;
  overflow-x: auto;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th,
td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #ddd;
}

th {
  background-color: #f2f2f2;
  font-weight: bold;
}

tr:hover {
  background-color: #f5f5f5;
}

.edit-btn,
.delete-btn {
  padding: 5px 10px;
  margin-right: 5px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.edit-btn {
  background-color: #4caf50;
  color: white;
}

.delete-btn {
  background-color: #f44336;
  color: white;
}
</style>
